package in.srain.cube.util.time;

import android.os.SystemClock;

import java.util.Date;

import in.srain.cube.request.JsonData;

/**
 * For:
 * l + offset = s
 * s = $server_time + rt / 2;
 * SO: offset = s - l = ($server_time + rt / 2) - l
 */
public final class TimeData {

    private static TimeData sInstance;

    private long mOffsetToServer = 0;
    private Date mLocalTime;
    private long mStartTime;

    private TimeData() {
        mLocalTime = new Date();
    }

    public static TimeData getInstance() {
        if (sInstance == null) {
            sInstance = new TimeData();
        }
        return sInstance;
    }

    public void sync(JsonData jsonData, long rt) {
        if (jsonData.has("serverTime")) {
            long serverTimeLong = jsonData.optLong("serverTime");
            mOffsetToServer = serverTimeLong + rt / 2 - System.currentTimeMillis();
            Date serverTime = new Date();
            serverTime.setTime(serverTimeLong);
        }
    }

    public Date getServerTime() {
        mLocalTime.setTime(System.currentTimeMillis() + mOffsetToServer);
        return mLocalTime;
    }

    public Date getServerTime(long time) {
        mLocalTime.setTime(time + mOffsetToServer);
        return mLocalTime;
    }

    public void initStartTime() {
        mStartTime = SystemClock.elapsedRealtime();
    }

    public long getUsedDuration() {
        return SystemClock.elapsedRealtime() - mStartTime;
    }
}
